/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.command;

import jp.aist.gtrc.plus.command.util.PlusReserveCommand;
import jp.aist.gtrc.plus.command.util.PlusReserveDestroyOptions;
import jp.aist.gtrc.plus.reserve.ReserveException;
import jp.aist.gtrc.plus.reserve.ReserveId;
import jp.aist.gtrc.plus.reserve.ReserveServer;
import jp.aist.gtrc.plus.reserve.ReserveStatus;


public class PlusReserveDestroy extends PlusReserveCommand {

	/*
	 * To Destroy:
	 * 	java PlusReserveDestroy {-r rsvId} {-o owner}
	 *
	 * To Show command help:
	 * 	java PlusReserve -h
	 */
	public static void main(String[] args){

		ReserveServer server = null;
		PlusReserveDestroyOptions options = new PlusReserveDestroyOptions("plus_destroy");
		ReserveId rsvId = null;
		String owner = null;

		try {
			options.parse(args);

			rsvId = options.getReserveId();
			owner = options.getOwner();
		} catch (Exception e) {
			showCommandHelp(options, e);
			System.exit(1);
		}

		try {
			server = getReserveServer(options);
			if (rsvId != null) {
				ReserveStatus status = server.getStatus(rsvId);
				if (getMyname().equals(status.getOwner()) == false)
					throw new ReserveException("You are not owner of this reserve");
				server.destroy(rsvId);
				if (options.isTransaction() == false) {
					server.commit(rsvId);
				}
				System.out.println("Reserve id = " + rsvId + " destroyed");
				if (options.isTransaction()) {
					System.out.println("You need plus_commit/plus_abort");
				}
			} else if (owner != null) {
				if (getMyname().equals(owner) == false)
					throw new ReserveException("You cannot destroy other's reserves");
				server.destroyOfOwner(owner);
				// committed automatically  by server
				System.out.println("All reserves owned by " + owner + " destroyed");
			}
		} catch (Exception e) {
			showException(e);
			System.exit(1);
		}

	}

}
